package org.smile.db.handler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.smile.beans.property.LikePropertyConverter;
import org.smile.beans.property.PropertyConverter;
import org.smile.db.util.ResultUtils;
/**
 * 把结果集转成Bean的RowHandler
 * 
 * 
 * @author strive
 *
 */
public class LikeBeanRowHandler implements RowHandler {
	/**
	 * bean的类型
	 */
	private Class type;
	PropertyConverter propertyConverter;
	public LikeBeanRowHandler(Class type){
		this.type=type;
		try {
			propertyConverter=new LikePropertyConverter(type);
		} catch (IntrospectionException e) {
			throw new RuntimeException("bean 属性转换失败",e);
		}
	}
	public Object handle(ResultSet rs) throws SQLException {
		Object bean;
		try{
			bean=type.newInstance();
			ResultSetMetaData rsmd = rs.getMetaData();
	        int cols = rsmd.getColumnCount();
	        for (int i = 1; i <= cols; i++) {
	        	String key = rsmd.getColumnLabel(i);
				PropertyDescriptor property=propertyConverter.keyToProperty(key);
				if(property!=null){
					Method setter=property.getWriteMethod();
					Class type=property.getPropertyType();
					if(setter!=null){
						Object value=ResultUtils.getColumn(rs, key, type);
						//转换类型
						setter.invoke(bean, new Object[]{value});
					}
				}
			}
		}catch(Exception e){
			throw new SQLException(e.toString());
		}
		return bean;
	}
	
}
